package websocketgulu.demo.Utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class SendMp3Utils {

    public static void SetResponse(String path, HttpServletResponse response) {
        ServletOutputStream servletOutputStream = null;
        int index = path.lastIndexOf( TestPathUtils.getFlag() );
        String fileName = path.substring(index);
        response.setHeader("content-type", "audio/mpeg");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            File file = new File(path);
            bis = new BufferedInputStream(new FileInputStream(file));
            int read = bis.read(buff);
            while (read != -1) {
                servletOutputStream.write(buff, 0, buff.length);
                servletOutputStream.flush();
                read = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (servletOutputStream != null)
                try {
                    servletOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}
